<template>
  <div ref="chart" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts'
import { debounce } from '@/utils'

export default {
  name: 'BoxplotChart',
  props: {
    chartData: {
      type: Object,
      required: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) return
    window.removeEventListener('resize', this.resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.setOptions(this.chartData)
    },
    setOptions({ xAxis, series } = {}) {
      if (!this.chart) return
      
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: xAxis || [],
          boundaryGap: true,
          nameGap: 30,
          axisLabel: {
            interval: 0,
            rotate: 30
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '信用分',
          splitArea: {
            show: true
          }
        },
        series: [
          {
            name: 'boxplot',
            type: 'boxplot',
            data: series || [],
            itemStyle: {
              color: '#3ba272'
            }
          }
        ]
      })
    },
    resizeHandler: debounce(function() {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
  }
}
</script>